package com.mmp.common.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mmp.common.bo.Message;
import com.mmp.main.entity.User;
import com.mmp.main.util.WebUtil;

public class LoginProcessServlet extends BasicServlet {

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		User user = new User();
		user.setUserName(WebUtil.getParamValue(request, "userName", null));
		user.setPassword(WebUtil.getParamValue(request, "password", null));
		// user.setStatus(true);
		// Employee emp = new Employee();
		// emp.setStatus(true);
		// user.setEmployee(emp);

		List<User> list = dbQueryManager.find(user);

		if (list == null || list.isEmpty() || list.size() != 1 || list.get(0).getStatus() == false) {
			setMessage(request, new Message("اسم المستخدم أو كلمة المرور غير صحيحة", Message.MESSAGE_TYPE.ERROR));
			basicForward(request, response, "Logout");
			return;
		}

		user = list.get(0);
		try {
			request.login(user.getUserName(), user.getPassword());
		} catch (Exception e) {
			e.printStackTrace();
			basicForward(request, response, "Logout");
			return;
		}
		setMessage(request, new Message("تم الدخول بنجاح", Message.MESSAGE_TYPE.SUCCESS));
		setSessionUser(request, user);

		if (WebUtil.userHasRightToChangeSessionHospital(request))
			sendRedirect(request, response, "ChooseSessionHospitalDisplay");
		else {
			setSessionLocation(request, dbQueryManager.getSiteLocations(user.getSite().getId()).get(0));
			sendRedirect(request, response, "UserProfileDisplay");
		}
	}
}
